package org.smart4j.framework.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/*
* 切面代理类，实现Proxy代理接口，进行真正的代理工作。
* 但仍然是一个抽象类，需要实现类去扩展其中的相应的抽象方法
* */
public abstract class AspectProxy implements Proxy {
    private static final Logger LOGGER = LoggerFactory.getLogger(AspectProxy.class);

    //真正的执行代理的过程
    @Override
    public Object doProxy(ProxyChain proxyChain) throws Throwable {
        Object result = null;

        Class<?> cls = proxyChain.getTargetClass();
        Method method = proxyChain.getTargetMethod();
        Object[] params = proxyChain.getMethodParams();

        begin();
        try {
            if (intercept(cls, method, params)){    //执行代理
                before(cls, method, params);
                result = proxyChain.doProxyChain(); //递归调用发生在这里
                after(cls, method, params);
            } else {                                //不执行代理
                result = proxyChain.doProxyChain();
            }
        } catch (Exception e){
            LOGGER.error("proxy failure", e);
            error(cls, method, params);
            throw e;
        } finally {
            end();
        }

        return result;
    }

    /*
    * 以下方法皆可以覆盖
    * */


    public void begin(){}

    //判断是否要执行代理方法，默认执行
    public boolean intercept(Class<?> cls, Method method, Object[] params){
        return true;
    }

    //前置增强，默认为空方法
    public void before(Class<?> cls, Method method, Object[] params) throws Throwable {

    }

    //后置增强，默认为空
    public void after(Class<?> cls, Method method, Object[] params)throws Throwable {

    }

    //抛出增强（错误处理代理），默认为空
    public void error(Class<?> cls, Method method, Object[] params)throws Throwable {

    }

    //finally 增强，默认为空
    public void end(){}
}
